package com.bawei.a2010douyin.ui.zhibo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.ui.widget.DanmakuView;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.bawei.a2010douyin.R;
import com.bawei.a2010douyin.annotation.LoginCheck;
import com.bawei.a2010douyin.base.mvp.BaseMvpActivity;
import com.bawei.a2010douyin.base.mvp.BasePresenter;
import com.bawei.a2010douyin.base.utils.ARouterPath;
import com.bawei.a2010douyin.base.utils.GlideUtils;
import com.bawei.a2010douyin.db.dao.DBUtils;
import com.bawei.a2010douyin.entity.ChatEntity;
import com.bawei.a2010douyin.entity.DanmakuEntity;
import com.bawei.a2010douyin.entity.GiftEntity;
import com.bawei.a2010douyin.entity.User;
import com.bawei.a2010douyin.entity.VideoEntity;
import com.bawei.a2010douyin.im.IMUtils;
import com.bawei.a2010douyin.pay.PayResult;
import com.bawei.a2010douyin.pay.util.OrderInfoUtil2_0;
import com.bawei.a2010douyin.widget.ChatRecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMMessage;
import com.kaisengao.likeview.like.KsgLikeView;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 1。视频播放器
 2。用户信息
 3。点赞
 4。全屏
 */
@Route(path = ARouterPath.ZHIBO_AROUTER_PATH)
public class ZhiBoActivity extends BaseMvpActivity<ZhiBoContract.IZhiBoView,ZhiBoPresenter> implements ZhiBoContract.IZhiBoView {
    @Autowired
    VideoEntity video;//名字必须保持一致 不能私有
    private StandardGSYVideoPlayer gsy;
    private ImageView ivUser;
    private TextView tvUsername;
    private TextView tvDianzanCount;
    private TextView tvGuanzhu;
    private TextView tvInput;
    private ImageView ivFull;
    private ImageView ivCar;
    private ImageView ivGift;
    private ImageView ivDianzan;
    private KsgLikeView ksgView;
    private ConstraintLayout clGift;
    private RecyclerView rvGift;
    private ImageView ivGiftSelect;
    private TextView tvGiftName;
    private GiftAdapter mGiftAdapter;
    private GiftEntity giftEntity;//选中的礼物
    private ConstraintLayout clZhibo;
    private DanmakuView flameView;//烈焰弹幕
    private LinearLayout llChatInput;
    private EditText etInput;
    private ImageView ivFasong;
    private ChatRecyclerView rvChat;//聊天列表
    private ChatAdapter mChatAdapter;
    private TextView tvMoney;



    //TODO 1:烈焰弹幕上下文
    private DanmakuContext mDanmakuContext;
    //TODO 2:烈焰弹幕解析器
    private BaseDanmakuParser mBaseDanmakuParser = new BaseDanmakuParser() {
        @Override
        protected IDanmakus parse() {
            return new Danmakus();
        }
    };
    //TODO 3:当activity获得焦点的时候，绘制烈焰弹幕
    @Override
    protected void onResume() {
        super.onResume();
        if(flameView != null){
            flameView.resume();
        }

    }



    //聊天室id
    private String chatRoomId = "211150599946242";
    //聊天室监听器
    private EMChatRoomChangeListener chatRoomChangeListener = new EMChatRoomChangeListener() {
        @Override
        public void onChatRoomDestroyed(String roomId, String roomName) {

        }

        @Override
        public void onMemberJoined(String roomId, String participant) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ChatEntity chatEntity = new ChatEntity(participant, "来了");
                    mChatAdapter.getData().add(chatEntity);
                    mChatAdapter.notifyDataSetChanged();
                    rvChat.scrollToPosition(mChatAdapter.getData().size()-1);
                }
            });
        }

        @Override
        public void onMemberExited(String roomId, String roomName, String participant) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ChatEntity chatEntity = new ChatEntity(participant, "走了");
                    mChatAdapter.getData().add(chatEntity);
                    mChatAdapter.notifyDataSetChanged();
                    rvChat.scrollToPosition(mChatAdapter.getData().size()-1);
                }
            });
        }

        @Override
        public void onRemovedFromChatRoom(int reason, String roomId, String roomName, String participant) {

        }

        @Override
        public void onMuteListAdded(String chatRoomId, List<String> mutes, long expireTime) {

        }

        @Override
        public void onMuteListRemoved(String chatRoomId, List<String> mutes) {

        }

        @Override
        public void onWhiteListAdded(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onWhiteListRemoved(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onAllMemberMuteStateChanged(String chatRoomId, boolean isMuted) {

        }

        @Override
        public void onAdminAdded(String chatRoomId, String admin) {

        }

        @Override
        public void onAdminRemoved(String chatRoomId, String admin) {

        }

        @Override
        public void onOwnerChanged(String chatRoomId, String newOwner, String oldOwner) {

        }

        @Override
        public void onAnnouncementChanged(String chatRoomId, String announcement) {

        }
    };
    //消息监听器
    private EMMessageListener msgListener = new EMMessageListener() {

        // 收到消息，遍历消息队列，解析和显示。
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    for (EMMessage message : messages) {
                        String from = message.getFrom();//来自谁
                        EMCustomMessageBody emCustomMessageBody = (EMCustomMessageBody) message.getBody();//消息体
                        String event = emCustomMessageBody.event();//类型
                        Map<String, String> params = emCustomMessageBody.getParams();//内容
                        if("text".equals(event)){//文本消息
                            ChatEntity chatEntity = new ChatEntity(from, params.get("message"));
                            mChatAdapter.getData().add(chatEntity);
                            mChatAdapter.notifyDataSetChanged();
                            rvChat.scrollToPosition(mChatAdapter.getData().size()-1);
                        }else if("gift".equals(event)){//礼物消息
                            ChatEntity chatEntity = new ChatEntity(from, "发送了一个"+params.get("name"));
                            mChatAdapter.getData().add(chatEntity);
                            mChatAdapter.notifyDataSetChanged();
                            rvChat.scrollToPosition(mChatAdapter.getData().size()-1);
                            //。。。。。。。。。。展示一个动画效果
                        }


                    }
                }
            });
        }
    };
    @Override
    public int bindLayout() {
        return R.layout.activity_zhi_bo;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);//接受数据必须注入
        tvMoney = (TextView) findViewById(R.id.tv_money);
        llChatInput = (LinearLayout) findViewById(R.id.ll_chat_input);
        etInput = (EditText) findViewById(R.id.et_input);
        ivFasong = (ImageView) findViewById(R.id.iv_fasong);
        flameView = (DanmakuView) findViewById(R.id.flame_view);
        gsy = (StandardGSYVideoPlayer) findViewById(R.id.gsy);
        ivUser = (ImageView) findViewById(R.id.iv_user);
        tvUsername = (TextView) findViewById(R.id.tv_username);
        tvDianzanCount = (TextView) findViewById(R.id.tv_dianzan_count);
        tvGuanzhu = (TextView) findViewById(R.id.tv_guanzhu);
        tvInput = (TextView) findViewById(R.id.tv_input);
        ivFull = (ImageView) findViewById(R.id.iv_full);
        ivCar = (ImageView) findViewById(R.id.iv_car);
        ivGift = (ImageView) findViewById(R.id.iv_gift);
        ivDianzan = (ImageView) findViewById(R.id.iv_dianzan);
        ksgView = (KsgLikeView) findViewById(R.id.ksg_view);
        clGift = (ConstraintLayout) findViewById(R.id.cl_gift);
        rvGift = (RecyclerView) findViewById(R.id.rv_gift);
        ivGiftSelect = (ImageView) findViewById(R.id.iv_gift_select);
        tvGiftName = (TextView) findViewById(R.id.tv_gift_name);
        clZhibo = (ConstraintLayout) findViewById(R.id.cl_zhibo);
        rvChat = (ChatRecyclerView) findViewById(R.id.rv_chat);
        //视频
        initGsy();
        //用户信息
        initUser();
        //礼物列表
        initGift();
        //烈焰弹幕
        initFlameDanMu();
        //聊天列表
        initChat();
        //加入聊天室
        initChatRoom();
        //显示当前余额
        float money = DBUtils.getInstance().getMoney();
        tvMoney.setText("余额："+money);

    }
    //加入聊天室
    private void initChatRoom() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 加入聊天室
                EMClient.getInstance().chatroomManager().joinChatRoom(chatRoomId, new EMValueCallBack<EMChatRoom>() {
                    @Override
                    public void onSuccess(EMChatRoom value) {
                        // 注册聊天室回调
                        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);
                        // 注册消息监听
                        EMClient.getInstance().chatManager().addMessageListener(msgListener);

                    }

                    @Override
                    public void onError(int error, String errorMsg) {

                    }
                });
            }
        }).start();
    }
    //退出聊天室
    @Override
    protected void onDestroy() {
        super.onDestroy();
        new Thread(new Runnable() {
            @Override
            public void run() {
                EMClient.getInstance().chatroomManager().leaveChatRoom(chatRoomId);
                // 移除聊天室回调
                EMClient.getInstance().chatroomManager().removeChatRoomListener(chatRoomChangeListener);
                // 解注册消息监听
                EMClient.getInstance().chatManager().removeMessageListener(msgListener);
            }
        }).start();
    }

    /**
     * 初始化聊天列表:从下向上滚动
     */
    private void initChat() {
        mChatAdapter = new ChatAdapter(R.layout.item_chat);
        rvChat.setAdapter(mChatAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setStackFromEnd(true);//从下向上滚动
        rvChat.setLayoutManager(linearLayoutManager);
    }

    /**
     * 初始化烈焰弹幕
     */
    private void initFlameDanMu() {
        flameView.enableDanmakuDrawingCache(true);//缓存
        flameView.setCallback(new DrawHandler.Callback() {
            @Override
            public void prepared() {//准备完成
                flameView.start();//启动
                //网络请求弹幕数据
                mPresenter.getDanMus(video.getId());
            }

            @Override
            public void updateTimer(DanmakuTimer timer) {

            }

            @Override
            public void danmakuShown(BaseDanmaku danmaku) {

            }

            @Override
            public void drawingFinished() {

            }
        });//回调
        mDanmakuContext = DanmakuContext.create();//获得上下文
        flameView.prepare(mBaseDanmakuParser,mDanmakuContext);//准备
    }

    private void initGift() {
        mGiftAdapter = new GiftAdapter(R.layout.item_gift);
        rvGift.setAdapter(mGiftAdapter);
        rvGift.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));
        //item的点击
        mGiftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                giftEntity = mGiftAdapter.getData().get(position);
                GlideUtils.getInstance().loadImage(ZhiBoActivity.this,giftEntity.getGiftpath(),ivGiftSelect);
                tvGiftName.setText(giftEntity.getGiftname()+"");
            }
        });
    }

    private void initUser() {
        GlideUtils.getInstance().loadCircleImage(this,video.getHeadpath(),ivUser);
        tvUsername.setText(video.getAuthname()+"");
        tvDianzanCount.setText(video.getLike_count()+"");
    }

    private void initGsy() {
        gsy.setUp(video.getVideopath(),true,"");
        gsy.getBackButton().setVisibility(View.GONE);
        //----横屏观看
        gsy.setShowFullAnimation(true);//动画效果
        gsy.setLockLand(true);//横屏观看
        gsy.setRotateViewAuto(true);//自动全凭
        //----
        gsy.startPlayLogic();
    }


    @Override
    public ZhiBoPresenter createPresenter() {
        return new ZhiBoPresenter();
    }

    @Override
    public void initData() {

    }

    /**
     * 点赞前需要登陆
     * @param view
     */
    @LoginCheck
    public void dianzan(View view) {
        ksgView.addLikeImages(R.drawable.ic_xihuanred,R.drawable.ic_xihuan,R.drawable.ic_fasong);
        ksgView.addFavor();
    }

    /**
     * 全屏观看
     * @param view
     */
    public void full(View view) {
        //actionBar隐藏 statusBar隐藏
        gsy.startWindowFullscreen(this,true,true);

    }

    /**
     * 点击事件：显示礼物框:入场动画
     * @param view
     */
    public void showgift(View view) {
        //入场动画
        clGift.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.in);
        animation.setInterpolator(new BounceInterpolator());//弹球效果
        clGift.startAnimation(animation);

        mPresenter.gift();//发起请求
    }

    /**
     * 点击事件：发送礼物判断是否登陆
     * @param view
     */
    @LoginCheck
    public void sendGift(View view) {
        //0：判断前够嘛
        float money = DBUtils.getInstance().getMoney();
        int price = giftEntity.getPrice();
        if(money < price){
            Toast.makeText(this, "你个穷鬼", Toast.LENGTH_SHORT).show();
            return;
        }



        //1：创建ImageView
        ImageView imageView = new ImageView(this);
        RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(200, 200);//图片的宽度和高度
        imageView.setLayoutParams(layoutParams);
        GlideUtils.getInstance().loadCircleImage(this,giftEntity.getGiftpath(),imageView);
        clZhibo.addView(imageView);
        //2:动画
        int width = clZhibo.getMeasuredWidth();
        int height = clZhibo.getMeasuredHeight();
        ObjectAnimator translationX = ObjectAnimator.ofFloat(imageView, "TranslationX", 0, width, 0, width / 2);
        ObjectAnimator translationY = ObjectAnimator.ofFloat(imageView, "TranslationY", 0, height/4, height/3, height / 2);
        ObjectAnimator rotation = ObjectAnimator.ofFloat(imageView, "Rotation", 0, 360);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(imageView, "ScaleX", 1, 3, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(imageView, "ScaleY", 1, 3, 1);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(2000);
        animatorSet.playTogether(translationX,translationY,rotation,scaleX,scaleY);
        animatorSet.start();
        //3:动画结束移除imageview+礼物框关闭
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                clZhibo.removeView(imageView);
                clGift.setVisibility(View.GONE);
                //出场动画
                Animation animation2 = AnimationUtils.loadAnimation(ZhiBoActivity.this, R.anim.out);
                clGift.startAnimation(animation2);

            }
        });
        //4：使用环信发送礼物
        HashMap<String,String> map = new HashMap<>();
        map.put("name",giftEntity.getGiftname());//礼物名称
        map.put("image",giftEntity.getGiftpath());//礼物图片
        IMUtils.getInstance().sendMessage("gift",map,chatRoomId);
        //5：更新余额:数据库+显示
        money-=price;
        User user = new User();
        user.setUsername(EMClient.getInstance().getCurrentUser());//当前登陆的用户
        user.setMoney(money);
        DBUtils.getInstance().updateMoney(user);
        tvMoney.setText("余额"+money);


    }

    /**
     * 点击事件：弹出输入框
     * @param view
     */
    public void showInput(View view) {
        llChatInput.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.in);
        llChatInput.startAnimation(animation);
        //编辑框自动获得焦点:直接输入内容即可，提供用户体验感
        etInput.requestFocus();
    }

    /**
     * 点击事件：发送消息前判断是否登陆
     * @param view
     */
    @LoginCheck
    public void sendMessage(View view) {
        Toast.makeText(this, "1111", Toast.LENGTH_SHORT).show();
        //消息显示在自己聊天框中
        String s = etInput.getText().toString();
        mChatAdapter.getData().add(new ChatEntity("yaotianxue",s));
        mChatAdapter.notifyDataSetChanged();
        rvChat.scrollToPosition(mChatAdapter.getData().size()-1);   //消息自动滚动到最新的一条
        //使用环信将消息发送出去
        HashMap<String, String> map = new HashMap<>();
        map.put("message",s);
        IMUtils.getInstance().sendMessage("text",map,chatRoomId);
    }

    /**
     * 点击事件：打开支付宝支付判断是否登陆
     * @param view
     */
    @LoginCheck
    public void zhifu(View view) {
//开启沙箱
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        pay();
    }

    /**
     * 礼物数据：展示recyclerview中
     * @param data
     */
    @Override
    public void showGift(List<GiftEntity> data) {
        mGiftAdapter.getData().addAll(data);
        mGiftAdapter.notifyDataSetChanged();
    }

    /**
     * 弹幕数据：展示烈焰弹幕中
     * @param data
     */
    @Override
    public void showDanmus(List<DanmakuEntity> data) {
        for (DanmakuEntity datum : data) {
            BaseDanmaku danmaku = mDanmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);//从右向左
            danmaku.text = datum.getText();
            danmaku.textColor = Color.GREEN;
            danmaku.borderColor = Color.RED;
            danmaku.textSize = 50;
            danmaku.setTime(datum.getTimestamp());//设置显示的时间
            flameView.addDanmaku(danmaku);
        }

    }



    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID =
            "2016103000779553";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";

    /**
     * pkcs8 格式的商户私钥。
     * <p>
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     * <p>
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCYJYflUySpQ//IL3wxdS937UV3iUw2VFXSYfq60DjS3/m73nM23uddswvuRoO+822JuekiXbfvkmGWYXNdXKqAoempPIl+ADxEXqvYGioyMLqVqV1meVQkGfVSr+CxQ9rkmdkVaKWqqDrVeFcUlN9ceW8YLJiKhpBT6hhqFPh7pngLIm6EotQ3mMNZoRID4yXpu8p6Eo8468Xr7mQZhfqGkjnXUWlhewBItZWdQ9JcwEsWsRUtCmk/BbAO+H7NrVv2oWREIacoKD0Ws79cAmdhQwsDFjnC/5qkb9hZj1ahhlS2zzEp6rhxERiI63+ee6sRO/pPJoaTTBUST0kpUcL5AgMBAAECggEAZ6urHae5o1yiPVWd2lVvMtiKLRlwxNRSZjg9EG4xSf8zu7+n4gugu0f1KTcDLmnQibgUE0aovqWPuVhNs6AgzeWFwbtuNF0Us8GOdoHdnrV1beUpr1mc67yEXQNap28FCB+Mu/nCaLaY4DxPmcaXK/vSpzY7+qgWUBeC60W+ywFlk2CNeJBTSmUTZSWimSv/f3x2/7biMdr1o+TF+tykK+A5yfIEZYXf4birzjAwVjtDSsetYAjRyuM7oR00leOB+U/WauxL4GsVadhcM9VIS8W3DE9kQbbH8BT8nk9x1lfOCYMb5EyI6f97lucUmneK3uPd+9na5dh/EhO4jHfIAQKBgQDWB/8HQmmCWnbT+dTY7QFxllCDBx13z0xYaUjmBOYKVSz3ouQSwtxsAY0IgqPdV26oRL5FOCaW7s4Wdg8cqLXYGZHHJ5Aby9clNEzPfQ0aHY6UQiIO512LotVpF7IzSAAP22rYApfiK1hlgBLB4No3bMbPOXNeqP1Itvq3bL0c8QKBgQC1+wgQnpocmk9ZznTEJh2kTNaO7GlLRyatQ8GYUMfAcq1plmlnXJyHwpGuLUSEcHofh394IhL09qqVceDpgqlp1RIXgCoiFLuM/KXTF3OJD+SCwgR9rYZNhbPcY6P+Whx8ngXAHdPoZWjeMx2mtZTDZ6b99V5F6RiPwjpeAOmmiQKBgBXXew8il+HVmYrIVBBPH3aYAF9euoMfhIsBM49FsLQdPRmIZf4EJLpg7iOQMWjFI2XIniIyOL3uYNmp8qDaFrSW52mLgAlWI/6H98601EF2ArbeiNs8gS9ezqiK4oSZNGhp291vZlCOW9b/2uouKBa/4woCsuNWG4LwKWXOkv4BAoGACt2PMLbXisen3zvVevSvpmS0FtqEuurno0a9Y2PHWXU/Z2OErZg4/F4gpp6rTaENmZ5UfQ7DxP6JVtzyyd50UQ5YwzBy05AbVqKrH/xxeIiLY0dET2Cx+ST3hTwpyYEF3Gbu/vaI9YJAjavNpGuJE1W4AcfJtjDht4uoQn6ZdMkCgYEAyR+e/PfxPevjzGmIBLZ+ZXnR1SVlQwda4/GrUyllUWf7akTSLkT+VvkfbcHaHB2Vil8LFYt/SKteKPBy7l0YRuNq74FLZka6Y6OmmemHXRSqOJzcEGyrOWT5ElLmywMltQK4s0VXwTAtsForDE4eqmuz1rZ0Er4rsKdVpdu/I5A=";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付成功");
                        Toast.makeText(ZhiBoActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        //更新钱
                        float money = DBUtils.getInstance().getMoney();//获得数据库钱
                        money+=1000;
                        User user = new User();
                        user.setUsername(EMClient.getInstance().getCurrentUser());//当前登陆的用户
                        user.setMoney(money);
                        DBUtils.getInstance().updateMoney(user);//更新
                        tvMoney.setText("余额:"+money);


                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付失败" + payResult);
                        Toast.makeText(ZhiBoActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

    /**
     * 支付宝支付业务示例
     */
    public void pay() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ZhiBoActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

}